/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package pt.mleiria.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

/**
 *
 * @author NB13712
 */
public class FileDigester {

    private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(FileDigester.class);

    private final byte[] raw;

    public FileDigester(final String pathToFile, final pt.mleiria.algorithm.MessageDigest md)
            throws NoSuchAlgorithmException, FileNotFoundException, IOException {

        final MessageDigest messageDigest = MessageDigest.getInstance(md.value());
        final File f = new File(pathToFile);
        final FileInputStream in = new FileInputStream(f);
        final FileChannel fchannel = in.getChannel();
        final ByteBuffer bytebuf = ByteBuffer.allocate((int)f.length());
        fchannel.read(bytebuf);
        messageDigest.update(bytebuf);
        /*
         byte[] buffer = new byte[(int)f.length()];
         int length;
         while((length = in.read(buffer)) != -1){
         messageDigest.update(buffer, 0, length);
         }
         */
        raw = messageDigest.digest();
    }
    public FileDigester(final String pathToFile, final pt.mleiria.algorithm.MessageAuthenticationCode md, final String pwd)
            throws NoSuchAlgorithmException, FileNotFoundException, IOException, InvalidKeyException {

        final File f = new File(pathToFile);
        final FileInputStream in = new FileInputStream(f);
        final FileChannel fchannel = in.getChannel();
        final ByteBuffer bytebuf = ByteBuffer.allocate((int)f.length());
        fchannel.read(bytebuf);
        final SecretKey key = new SecretKeySpec(pwd.getBytes("UTF-8"), md.value());
        final Mac m = Mac.getInstance(md.value());
        m.init(key);
        m.update(bytebuf);
        raw = m.doFinal();
    }

    public byte[] getRaw() {
        return raw;
    }

    public String getRawBase64() throws UnsupportedEncodingException {
        return new String(Base64.encodeBase64(raw), "UTF-8");
    }

}
